const bcrypt = require('bcrypt');
const { User, Document, DocumentCollaborator, Topic } = require('./db');

module.exports = (express) => {
  const router = express.Router();

  // 中间件
  router.use(express.json());

  // 用户注册
  router.post('/register', (req, res) => {
    const { username, password } = req.body;
    
    if (!username || !password) {
      return res.status(400).json({ error: 'Username and password are required' });
    }
    
    // 检查用户是否已存在
    User.findByUsername(username, (err, user) => {
      if (err) {
        return res.status(500).json({ error: 'Database error' });
      }
      
      if (user) {
        return res.status(400).json({ error: 'User already exists' });
      }
      
      // 加密密码
      bcrypt.hash(password, 10, (err, hash) => {
        if (err) {
          return res.status(500).json({ error: 'Error hashing password' });
        }
        
        // 创建用户
        User.create(username, hash, (err, userId) => {
          if (err) {
            return res.status(500).json({ error: 'Error creating user' });
          }
          
          res.status(201).json({ 
            message: 'User created successfully',
            user: { id: userId, username }
          });
        });
      });
    });
  });

  // 用户登录
  router.post('/login', (req, res) => {
    const { username, password } = req.body;
    
    if (!username || !password) {
      return res.status(400).json({ error: 'Username and password are required' });
    }
    
    // 查找用户
    User.findByUsername(username, (err, user) => {
      if (err) {
        return res.status(500).json({ error: 'Database error' });
      }
      
      if (!user) {
        // 如果用户不存在，自动创建账户
        bcrypt.hash(password, 10, (err, hash) => {
          if (err) {
            return res.status(500).json({ error: 'Error hashing password' });
          }
          
          User.create(username, hash, (err, userId) => {
            if (err) {
              return res.status(500).json({ error: 'Error creating user' });
            }
            
            res.json({ 
              message: 'User created and logged in successfully',
              user: { id: userId, username }
            });
          });
        });
      } else {
        // 验证密码
        bcrypt.compare(password, user.password, (err, result) => {
          if (err) {
            return res.status(500).json({ error: 'Error comparing passwords' });
          }
          
          if (result) {
            res.json({ 
              message: 'Login successful',
              user: { id: user.id, username: user.username }
            });
          } else {
            res.status(401).json({ error: 'Invalid password' });
          }
        });
      }
    });
  });

  // 获取用户文档列表（树形结构）
  router.get('/documents/user/:userId', (req, res) => {
    const userId = req.params.userId;
    
    Document.findByUserId(userId, (err, documents) => {
      if (err) {
        return res.status(500).json({ error: 'Database error' });
      }
      
      res.json({ documents });
    });
  });

  // 获取用户文档树形结构
  router.get('/documents/user/:userId/tree', (req, res) => {
    const userId = req.params.userId;
    
    Document.findByUserId(userId, (err, documents) => {
      if (err) {
        return res.status(500).json({ error: 'Database error' });
      }
      
      // 构建树形结构
      const tree = Document.buildTree(documents);
      res.json({ tree });
    });
  });

  // 获取指定父级的子项
  router.get('/documents/children/:parentId/:userId', (req, res) => {
    const { parentId, userId } = req.params;
    
    Document.findByParentId(parentId === 'null' ? null : parseInt(parentId), userId, (err, documents) => {
      if (err) {
        return res.status(500).json({ error: 'Database error' });
      }
      
      res.json({ documents });
    });
  });

  // 创建文档或文件夹
  router.post('/documents', (req, res) => {
    const { title, content, type, parentId, ownerId, topicId } = req.body;
    
    // 验证类型
    const documentType = type || 'document';
    if (!['folder', 'document'].includes(documentType)) {
      return res.status(400).json({ error: 'Type must be either "folder" or "document"' });
    }
    
    Document.create(title, content, documentType, parentId, ownerId, topicId, (err, documentId) => {
      if (err) {
        return res.status(500).json({ error: 'Database error' });
      }
      
      res.status(201).json({ 
        message: 'Document created successfully',
        document: { id: documentId, title, content, type: documentType, parentId, ownerId, topicId }
      });
    });
  });

  // 获取文档详情
  router.get('/documents/:id', (req, res) => {
    const id = req.params.id;
    
    Document.findById(id, (err, document) => {
      if (err) {
        return res.status(500).json({ error: 'Database error' });
      }
      
      if (!document) {
        return res.status(404).json({ error: 'Document not found' });
      }
      
      res.json({ document });
    });
  });

  // 更新文档
  router.put('/documents/:id', (req, res) => {
    const id = req.params.id;
    const { title, content } = req.body;
    
    Document.update(id, title, content, (err, changes) => {
      if (err) {
        return res.status(500).json({ error: 'Database error' });
      }
      
      if (changes === 0) {
        return res.status(404).json({ error: 'Document not found' });
      }
      
      res.json({ message: 'Document updated successfully' });
    });
  });

  // 移动文档到不同的父级
  router.put('/documents/:id/move', (req, res) => {
    const id = req.params.id;
    const { parentId } = req.body;
    
    Document.move(id, parentId, (err, changes) => {
      if (err) {
        return res.status(500).json({ error: 'Database error' });
      }
      
      if (changes === 0) {
        return res.status(404).json({ error: 'Document not found' });
      }
      
      res.json({ message: 'Document moved successfully' });
    });
  });

  // 删除文档或文件夹
  router.delete('/documents/:id', (req, res) => {
    const id = req.params.id;
    
    Document.delete(id, (err, changes) => {
      if (err) {
        return res.status(500).json({ error: 'Database error' });
      }
      
      if (changes === 0) {
        return res.status(404).json({ error: 'Document not found' });
      }
      
      res.json({ message: 'Document deleted successfully' });
    });
  });

  // ======================== 主题(Topic)管理 API ========================

  // 获取所有主题
  router.get('/topics', (req, res) => {
    Topic.findAll((err, topics) => {
      if (err) {
        return res.status(500).json({ error: 'Database error' });
      }
      
      res.json({ topics });
    });
  });

  // 获取默认主题
  router.get('/topics/default', (req, res) => {
    Topic.findDefault((err, topic) => {
      if (err) {
        return res.status(500).json({ error: 'Database error' });
      }
      
      if (!topic) {
        return res.status(404).json({ error: 'Default topic not found' });
      }
      
      res.json({ topic });
    });
  });

  // 获取指定主题
  router.get('/topics/:id', (req, res) => {
    const id = req.params.id;
    
    Topic.findById(id, (err, topic) => {
      if (err) {
        return res.status(500).json({ error: 'Database error' });
      }
      
      if (!topic) {
        return res.status(404).json({ error: 'Topic not found' });
      }
      
      res.json({ topic });
    });
  });

  // 创建主题
  router.post('/topics', (req, res) => {
    const { title, description, color, icon, createdBy } = req.body;
    
    if (!title) {
      return res.status(400).json({ error: 'Topic title is required' });
    }
    
    Topic.create(title, description, color, icon, createdBy, (err, topicId) => {
      if (err) {
        return res.status(500).json({ error: 'Database error' });
      }
      
      res.status(201).json({ 
        message: 'Topic created successfully',
        topic: { id: topicId, title, description, color, icon, createdBy }
      });
    });
  });

  // 更新主题
  router.put('/topics/:id', (req, res) => {
    const id = req.params.id;
    const { title, description, color, icon } = req.body;
    
    if (!title) {
      return res.status(400).json({ error: 'Topic title is required' });
    }
    
    Topic.update(id, title, description, color, icon, (err, changes) => {
      if (err) {
        return res.status(500).json({ error: 'Database error' });
      }
      
      if (changes === 0) {
        return res.status(404).json({ error: 'Topic not found' });
      }
      
      res.json({ message: 'Topic updated successfully' });
    });
  });

  // 设置默认主题
  router.put('/topics/:id/default', (req, res) => {
    const id = req.params.id;
    
    Topic.setDefault(id, (err, changes) => {
      if (err) {
        return res.status(500).json({ error: 'Database error' });
      }
      
      if (changes === 0) {
        return res.status(404).json({ error: 'Topic not found' });
      }
      
      res.json({ message: 'Default topic updated successfully' });
    });
  });

  // 删除主题
  router.delete('/topics/:id', (req, res) => {
    const id = req.params.id;
    
    Topic.delete(id, (err, changes) => {
      if (err) {
        return res.status(500).json({ error: err.message || 'Database error' });
      }
      
      if (changes === 0) {
        return res.status(404).json({ error: 'Topic not found or cannot delete default topic' });
      }
      
      res.json({ message: 'Topic deleted successfully' });
    });
  });

  // 获取主题下的文档数量
  router.get('/topics/:id/documents/count', (req, res) => {
    const id = req.params.id;
    
    Topic.getDocumentCount(id, (err, count) => {
      if (err) {
        return res.status(500).json({ error: 'Database error' });
      }
      
      res.json({ count });
    });
  });

  return router;
};